package com.example.feidaolumanager


import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelProvider
import com.example.feidaolumanager.api.RetrofitClient
import com.example.feidaolumanager.pages.MainActivity
import com.example.feidaolumanager.pages.RegisterActivity
import com.example.feidaolumanager.pojo.LoginVo
import com.example.feidaolumanager.pojo.User
import com.example.feidaolumanager.ui.theme.FeidaoluManagerTheme
import com.example.feidaolumanager.viewModel.LoginViewModel
import com.google.gson.Gson

class LoginActivity : ComponentActivity() {
    // At the top level of your kotlin file:

    private val TAG: String = this.toString()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val sharedPref: SharedPreferences =
            this@LoginActivity.getSharedPreferences(Constants.store_key, Context.MODE_PRIVATE)

        val loginViewModel = ViewModelProvider(this)[LoginViewModel::class.java]


        val userStr = sharedPref.getString("user", "")

        RetrofitClient.context = baseContext
        if (userStr!!.isNotEmpty()) {
            val user = Gson().fromJson(userStr, User::class.java)
//            RetrofitClient.token = user.token
            loginViewModel.user.value = user
            // 结束当前页面
            finish()
            // 跳转主页面
            baseContext.startActivity(
                Intent(
                    baseContext,
                    MainActivity::class.java
                ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .putExtra("user", user)
            )
        }


        loginViewModel.user.observe(this) {

            Log.e(TAG, "onCreate: 不应该有值$it")

            if (it != null) {
//                RetrofitClient.token = it.token
                with(sharedPref.edit()) {
                    // 把登录获取到的用户信息持久化到本地
                    putString("user", Gson().toJson(it))
                    apply()
                }
            }
        }

        loginViewModel.loginSuccess.observe(this) {
            if (it == true) {
                // 结束当前页面
                finish()
                // 跳转主页面
                baseContext.startActivity(
                    Intent(
                        baseContext,
                        MainActivity::class.java
                    ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .putExtra("user", loginViewModel.user.value)
                )
            } else if (it == false) {
                Toast.makeText(baseContext, "账号密码错误", Toast.LENGTH_LONG).show()
            }

        }

        setContent {
            FeidaoluManagerTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier
                        .fillMaxSize(),
                ) {
                    Greeting(loginViewModel, this@LoginActivity)
                }
            }
        }
    }
}

@Composable
fun Greeting(loginViewModel: LoginViewModel, loginActivity: LoginActivity) {

    // data

    // template
    Column(
        modifier = Modifier
            .fillMaxSize()
            .paint(
                painterResource(id = R.drawable.bg),
                contentScale = ContentScale.FillBounds
            ),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {


        Spacer(modifier = Modifier.height(100.dp))

        Image(
            modifier = Modifier
                .height(50.dp)
                .width(50.dp),
            painter = painterResource(id = R.drawable.jxyd),
            contentDescription = "jxyd的公司logo"
        )
        Text(
            text = "非道路机械管理平台",
            modifier = Modifier,
            color = Color.White,
            fontSize = 20.sp
        )

        var account by remember {
            mutableStateOf("")
        }

        var accountErrorMsg by remember {
            mutableStateOf("")
        }

        MyTextField(label = "账号", field = account, errorMsg = accountErrorMsg) {
            account = it
        }
        var password by remember {
            mutableStateOf("")
        }

        var passwordErrorMsg by remember {
            mutableStateOf("")
        }

        MyTextField(label = "密码", field = password, errorMsg = passwordErrorMsg) {
            password = it
        }

        Button(onClick = {
            // 验证通过后登录
            accountErrorMsg = if (account.isEmpty()) {
                "账号不能为空！"
            } else {
                ""
            }

            passwordErrorMsg = if (password.isEmpty()) {
                "密码不能为空"
            } else {
                ""
            }

            if (accountErrorMsg.isEmpty() && passwordErrorMsg.isEmpty()) {
                // 验证通过调用登录接口

                Log.i(this.toString(), "用户名：$account, 密码:$password")
                loginViewModel.login(LoginVo(account, password))


            }
        }) {
            Text(text = "登录")
        }


        Button(onClick = {
            // 点击跳转到注册界面
            loginActivity.startActivity(Intent(loginActivity, RegisterActivity::class.java))
        }, colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent)) {
            Text(text = "新用户注册")
        }
    }
}

@Composable
@OptIn(ExperimentalMaterial3Api::class)
fun MyTextField(
    label: String, field: String, errorMsg: String, onFieldChange: (String) -> Unit
) {

    TextField(
        value = field,
        onValueChange = onFieldChange,
        modifier = Modifier
            .background(color = Color.Transparent)
            .fillMaxWidth(),
        label = {
            Text(text = label)
        },
        placeholder = {
            Text(text = "请输入$label!")
        },
        trailingIcon = {
            if (field.isNotEmpty()) {
                Icon(imageVector = Icons.Filled.Clear, contentDescription = "清除按钮",
                    Modifier.clickable {
                        onFieldChange("")
                    })
            } else {
                Spacer(modifier = Modifier)
            }
        },
        colors = TextFieldDefaults.textFieldColors(
            containerColor = Color.Transparent,
        )
    )

    Text(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 50.dp),
        text = errorMsg,
        color = Color.Red
    )
}